﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Shapes;
using System.Windows.Media;
using Chromatics.Pages.Palette;
using Chromatics.Pages.CustomLine;
using System.Threading;
using Chromatics.Pages.CustomMessageBox;
using System.Windows.Threading;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using Microsoft.Advertising.Mobile.UI;

namespace Chromatics
{
    public partial class GamePage : PhoneApplicationPage
    {
        private GameLogic gameLogic;
        private List<CustomLine> edgesList = null;
        private int ellipseD = 50;
        private UserControl control = null;
        private bool controlNeedToHide = false;
        private PageOrientation currentOrientation = PageOrientation.PortraitUp;
        private Ellipse currentEllipse = null;
        private Dictionary<Edge, CustomLine> edgeLineDict;
        private CustomMessageBox messageBox;
        private bool gameIsRunnig = false;

        public GamePage()
        {
            InitializeComponent();
            this.gameLogic = new GameLogic();
            this.messageBox = new CustomMessageBox();
            this.messageBox.NextLevelBtn.Tap += NextLevelBtn_Tap;
            this.messageBox.PlayAgainBtn.Tap += PlayAgainBtn_Tap;
        }

        void PlayAgainBtn_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            SoundPlayer.PlayDing();
            //play again
            this.ContentPanel.Children.Clear();
            this.ContentPanel.Children.Add(levelNumbAndDiff);
            //this.ContentPanel.Children.Add(Advertising);
            this.gameLogic.ResetCurrentLevel();
            this.InitializeComponent();
            loadLvl();
        }

        void NextLevelBtn_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            SoundPlayer.PlayDing();
            //next level
            this.ContentPanel.Children.Clear();
            this.ContentPanel.Children.Add(levelNumbAndDiff);
            //this.ContentPanel.Children.Add(Advertising);
            this.gameLogic.NextLevel();
            this.InitializeComponent();
            loadLvl();
        }

        private void loadLvl()
        {
            levelNumbAndDiff.Text = "Level: " + GameLogic.CurrentLevelNumber + "    Difficulty: " + GameLogic.CurrentDifficulty.ToString();
            this.edgesList = new List<CustomLine>();
            this.edgeLineDict = new Dictionary<Edge, CustomLine>();
            this.messageBox.Visibility = System.Windows.Visibility.Collapsed;
            this.messageBox.IsEnabled = false;

            for (int i = 0; i < this.gameLogic.GetGraph.Edges.Count; i++)
            {
                CustomLine line = new CustomLine();
                line.X1 = this.gameLogic.GetGraph.Peaks[this.gameLogic.GetGraph.Edges[i].Start].X;
                line.Y1 = this.gameLogic.GetGraph.Peaks[this.gameLogic.GetGraph.Edges[i].Start].Y;
                line.X2 = this.gameLogic.GetGraph.Peaks[this.gameLogic.GetGraph.Edges[i].Finish].X;
                line.Y2 = this.gameLogic.GetGraph.Peaks[this.gameLogic.GetGraph.Edges[i].Finish].Y;

                line.StrokeThickness = 7;
                line.Name = "Line " + i.ToString();

                this.edgeLineDict.Add(this.gameLogic.GetGraph.Edges[i], line);
                this.edgesList.Add(line);
                this.ContentPanel.Children.Add(line);
            }

            for (int i = 0; i < this.gameLogic.GetGraph.Peaks.Count; i++)
            {
                //Transparency elipse
                Ellipse elps = new Ellipse();
                elps.Height = ellipseD + 50;
                elps.Width = ellipseD + 50;
                elps.Margin = new Thickness(this.gameLogic.GetGraph.Peaks[i].X - (ellipseD + 50) / 2, this.gameLogic.GetGraph.Peaks[i].Y - (ellipseD + 50) / 2, 0, 0);
                elps.Fill = new SolidColorBrush(Colors.Transparent);

                elps.Stroke = new SolidColorBrush(Colors.Transparent); //Black for testing
                elps.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                elps.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                elps.Name = "TransEllipse " + i.ToString();

                elps.Tap += TransEllipse_Tap;
                this.ContentPanel.Children.Add(elps);

                //Real elipse
                Ellipse ellipse = new Ellipse();
                ellipse.Height = ellipseD;
                ellipse.Width = ellipseD;
                ellipse.Margin = new Thickness(this.gameLogic.GetGraph.Peaks[i].X - ellipseD / 2, this.gameLogic.GetGraph.Peaks[i].Y - ellipseD / 2, 0, 0);
                ellipse.Fill = new SolidColorBrush(PalleteColors.Default);
                ellipse.Stroke = new SolidColorBrush(Colors.Black);
                ellipse.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                ellipse.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                ellipse.Name = "Ellipse " + i.ToString();

                ellipse.Tap += ellipse_Tap;

                this.ContentPanel.Children.Add(ellipse);
            }
            this.control = new EvenPallete(6);
            ((EvenPallete)this.control).BlueArc.Tap += BlueArc_Tap;
            ((EvenPallete)this.control).RedArc.Tap += RedArc_Tap;
            ((EvenPallete)this.control).YellowArc.Tap += YellowArc_Tap;
            ((EvenPallete)this.control).GreenArc.Tap += GreenArc_Tap;
            ((EvenPallete)this.control).AzureArc.Tap += AzureArc_Tap;
            ((EvenPallete)this.control).OrangeArc.Tap += OrangeArc_Tap;
            //additional
            ((EvenPallete)this.control).BlueArc_Copy.Tap += BlueArc_Tap;
            ((EvenPallete)this.control).RedArc_Copy.Tap += RedArc_Tap;
            ((EvenPallete)this.control).YellowArc_Copy.Tap += YellowArc_Tap;
            ((EvenPallete)this.control).GreenArc_Copy.Tap += GreenArc_Tap;
            ((EvenPallete)this.control).AzureArc_Copy.Tap += AzureArc_Tap;
            ((EvenPallete)this.control).OrangeArc_Copy.Tap += OrangeArc_Tap;

            this.control.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            this.control.VerticalAlignment = System.Windows.VerticalAlignment.Top;
            this.control.Visibility = System.Windows.Visibility.Collapsed;
            this.ContentPanel.Children.Add(control);

            this.ContentPanel.Children.Add(this.messageBox);
        }

        private int getPeakNumber()
        {
            string name = this.currentEllipse.Name;
            return int.Parse(name.Split(' ')[1]);
        }

        private void setEllipseColor(Color color1, Color color2, LevelState levelState)
        {
            RadialGradientBrush brush = new RadialGradientBrush();
            brush.GradientStops.Add(new GradientStop() { Color = color2, Offset = 1 });
            brush.GradientStops.Add(new GradientStop() { Color = color1, Offset = 0.2 });
           
            this.currentEllipse.Fill = brush;
            this.control.Visibility = System.Windows.Visibility.Collapsed;

            foreach (CustomLine line in this.edgesList)
            {
                line.Stop();
            }

            if (this.gameLogic.GetErrorEdges().Count > 0)
            {
                SoundPlayer.StartErrorSound();
            }
            else
            {
                SoundPlayer.StopErrorSound();
            }

            foreach (Edge edge in this.gameLogic.GetErrorEdges())
            {
                this.edgeLineDict[edge].Run();
            }

            if (levelState == LevelState.Accepted)
            {
                DispatcherTimer timer = new DispatcherTimer();
                timer.Interval = new TimeSpan(0, 0, 0, 0, 50);
                timer.Tick += new EventHandler(Timer_Tick);
                timer.Start();
            }
        }

        void Timer_Tick(object sender, EventArgs e)
        {
            this.gameLogic.CompleteCurrentLevel();

            //if game is completed
            if (GameLogic.CurrentDifficulty == Difficulty.Hard && GameLogic.CurrentLevelNumber == DataLoader.Instance.LevelsCount(Difficulty.Hard))
            {
                SoundPlayer.PlayDing();
                NavigationService.Navigate(new Uri("/Pages/CongratilationsPage.xaml", System.UriKind.Relative));
            }
            this.messageBox.Visibility = System.Windows.Visibility.Visible;
            this.messageBox.Run(this.gameLogic.GetStarsForCurrentLevel());
            this.messageBox.IsEnabled = true;
            
            if (this.gameLogic.isNextLevelLocked() == true)
            {
                this.messageBox.SetNextDisabled();
            }
            else
            {
                this.messageBox.SetNextEnabled();
            }
            ((DispatcherTimer)sender).Stop();
        }

        void OrangeArc_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            setEllipseColor(PalleteColors.Orange, PalleteColors.DarkOrange, this.gameLogic.SetPeakColor(getPeakNumber(), PalleteColors.Orange));
            //Advertising.IsAutoRefreshEnabled = true;
        }

        void AzureArc_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            setEllipseColor(PalleteColors.Azure, PalleteColors.DarkAzure, this.gameLogic.SetPeakColor(getPeakNumber(), PalleteColors.Azure));
            //Advertising.IsAutoRefreshEnabled = true;
        }

        void GreenArc_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            setEllipseColor(PalleteColors.Green, PalleteColors.DarkGreen, this.gameLogic.SetPeakColor(getPeakNumber(), PalleteColors.Green));
            //Advertising.IsAutoRefreshEnabled = true;
        }

        void YellowArc_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            setEllipseColor(PalleteColors.Yellow, PalleteColors.DarkYellow, this.gameLogic.SetPeakColor(getPeakNumber(), PalleteColors.Yellow));
            //Advertising.IsAutoRefreshEnabled = true;
        }

        void RedArc_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            setEllipseColor(PalleteColors.Red, PalleteColors.DarkRed, this.gameLogic.SetPeakColor(getPeakNumber(), PalleteColors.Red));
            //Advertising.IsAutoRefreshEnabled = true;
        }

        void BlueArc_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            setEllipseColor(PalleteColors.Blue, PalleteColors.DarkBlue, this.gameLogic.SetPeakColor(getPeakNumber(), PalleteColors.Blue));
            //Advertising.IsAutoRefreshEnabled = true;
        }

        private void TransEllipse_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            int number = int.Parse(((Ellipse)sender).Name.Split(' ')[1]);
            Object trueSender = this.ContentPanel.Children.Where(a=>a is Ellipse).First(b =>((Ellipse)b).Name  == "Ellipse " + number.ToString());

            this.ellipse_Tap(trueSender, e);
        }

        private void ellipse_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (this.messageBox.Visibility == System.Windows.Visibility.Visible)
            {
                return;
            }

            //Advertising.IsAutoRefreshEnabled = false;

            SoundPlayer.PlayDrop();

            this.currentEllipse = (Ellipse)sender;
            double currentX = ((Ellipse)sender).Margin.Left, currentY = ((Ellipse)sender).Margin.Top;
            if (this.currentOrientation == PageOrientation.PortraitUp)
            {
                currentX -= 50;
                currentY -= 62;
                this.control.RenderTransform = null;
            }
    
            this.control.Margin = new Thickness(currentX, currentY, 0, 0);
            this.control.Visibility = System.Windows.Visibility.Visible;
            this.controlNeedToHide = false;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (this.gameIsRunnig == false)
            {
                this.gameLogic.SetLevel();
                this.loadLvl();
                this.gameIsRunnig = true;
            }
        }

        private void mainPage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (this.controlNeedToHide == false)
            {
                this.controlNeedToHide = true;
            }
            else
            {
                this.control.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        private void mainPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            SoundPlayer.StopErrorSound();
            SoundPlayer.PlayDing();
        }

        //Hide AdControl when it has error while loading
        //private void AdControl_ErrorOccurred_1(object sender, Microsoft.Advertising.AdErrorEventArgs e)
        //{
        //    AdControl ad = (AdControl)sender;
        //    Dispatcher.BeginInvoke(() => { ad.Visibility = System.Windows.Visibility.Collapsed; });
        //}

        //show AdControl after hiding when it refreshed
        //private void AdControl_AdRefreshed_1(object sender, EventArgs e)
        //{
        //    AdControl ad = (AdControl)sender;
        //    if (ad.Visibility != System.Windows.Visibility.Visible)
        //        Dispatcher.BeginInvoke(() => {ad.Visibility = System.Windows.Visibility.Visible;});
        //}
    }

}